#创建一个浏览器对象
import datetime
import os
import sys
from selenium import webdriver
from selenium.webdriver import ActionChains, Keys
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager


class Driver:
    driver = ""
    def __init__(self):
        options = webdriver.ChromeOptions()
        self.driver = webdriver.Chrome(service = Service(ChromeDriverManager().install()),options = options)
        #添加隐式等待：因为隐式等待的作用域在driver的整个生命周期
        self.driver.implicitly_wait(3)


    def getScreenshot(self):
        # 创建屏幕截图
        # 图片文件名称：./2024-05-08-173456.png
        dirname = datetime.datetime.now().strftime("%Y-%m-%d")
        # 判断dirname文件夹是否已经存在，若不存在则创建文件夹
        # ../images/2024-05-08
        if not os.path.exists("../images/" + dirname):
            os.mkdir("../images/" + dirname)
        # 2024-05-08-173456.png
        # 图片路径:../images/调用方法-2024-05-08/2024-05-08-173456.png
        # 图片路径:../images/LoginSucTest-2024-05-08/2024-05-08-173456.png
        # 图片路径:../images/LoginFailTest-2024-05-08/2024-05-08-173456.png
        filename = sys._getframe().f_back.f_code.co_name + "-" + datetime.datetime.now().strftime(
            "%Y-%m-%d-%H%M%S") + ".png"
        self.driver.save_screenshot("../images/" + dirname + "/" + filename)


    #由于项目外层不是一个单纯的input标签，而是组件封装之后的，所以不能使用selenium中的clear()
    #清空指定输入框的内容
    def clear(self, element):
        actions = ActionChains(self.driver)
        actions.click(element)  # 点击元素
        actions.key_down(Keys.CONTROL).send_keys("a").key_up(Keys.CONTROL)  # Ctrl+A
        actions.send_keys(Keys.DELETE)  # 删除
        actions.perform()  # 执行所有动作


QE_Driver = Driver()